const path = require("path");
const CopyPlugin = require("copy-webpack-plugin");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const CssMinimizerPlugin = require("css-minimizer-webpack-plugin");
const TerserPlugin = require("terser-webpack-plugin");
const ZipPlugin = require("zip-webpack-plugin");

module.exports = (env, argv) => {
  const isProduction = argv.mode === "production";

  return {
    entry: {
      background: "./js/background.js",
      content: "./js/content.js",
      popup: "./js/popup.js",
    },
    output: {
      path: path.resolve(__dirname, "dist"),
      filename: "js/[name].js",
      clean: true,
    },
    module: {
      rules: [
        {
          test: /\.js$/,
          exclude: /node_modules/,
          use: {
            loader: "babel-loader",
            options: {
              presets: ["@babel/preset-env"],
            },
          },
        },
        {
          test: /\.css$/,
          use: [MiniCssExtractPlugin.loader, "css-loader"],
        },
        {
          test: /\.(png|svg|jpg|jpeg|gif)$/i,
          type: "asset/resource",
          generator: {
            filename: "images/[name][ext]",
          },
        },
      ],
    },
    plugins: [
      new CopyPlugin({
        patterns: [
          {
            from: "manifest.json",
            to: "manifest.json",
            transform(content) {
              // 在生产环境中移除不必要的权限或注释
              if (isProduction) {
                const manifest = JSON.parse(content.toString());
                return JSON.stringify(manifest, null, isProduction ? 0 : 2);
              }
              return content;
            },
          },
          { from: "images", to: "images" },
          { from: "css", to: "css" },
        ],
      }),
      new HtmlWebpackPlugin({
        template: "./popup/popup.html",
        filename: "popup/popup.html",
        chunks: ["popup"],
      }),
      new MiniCssExtractPlugin({
        filename: "css/[name].css",
      }),
      // 仅在生产模式下添加zip打包
      ...(isProduction
        ? [
            new ZipPlugin({
              path: path.resolve(__dirname, "dist"),
              filename: "quick-input-plugin.zip",
              pathPrefix: "",
            }),
          ]
        : []),
    ],
    optimization: {
      minimizer: [
        new TerserPlugin({
          terserOptions: {
            format: {
              comments: false,
            },
            compress: {
              drop_console: isProduction,
              drop_debugger: isProduction,
            },
          },
          extractComments: false,
        }),
        new CssMinimizerPlugin(),
      ],
      minimize: isProduction,
    },
    devtool: isProduction ? false : "source-map",
    mode: isProduction ? "production" : "development",
  };
};
